//
//  SWPictureImageView.swift
//  SinaWeibo
//
//  Created by wszyxc on 16/7/25.
//  Copyright © 2016年 wszyxc. All rights reserved.
//

import UIKit
import SnapKit

private let SWPictureImageViewCellID = "SWPictureImageViewCellID"


let ItemWH:CGFloat = 80

let ItemMargin:CGFloat = 10


class SWPictureCollectionView: UICollectionView {
    
    
    var constraits:Constraint?
    
    var dataArray:[SWPictureModel]?{
        
        
        
        didSet{

          //  constraits?.uninstall()

            
            let col =  (dataArray!.count == 4) ? 2: (dataArray!.count>3 ?3 :dataArray?.count)
            let row =   ((dataArray?.count)! - 1)/3 + 1
            
            let w = CGFloat(col!) * ItemWH + CGFloat(col!-1) * ItemMargin
            let h = CGFloat(row) * ItemWH + CGFloat(row-1) * ItemMargin
            
            //设置约束---size
            self.snp_updateConstraints { (make) -> Void in
             
                    make.size.equalTo(CGSizeMake(w, h)).priorityLow()

            }
            
            reloadData()
            
        }
        
    }


   override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: layout)
    
        setupUI()
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
    private func setupUI(){
        
        //设置视图
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        flowLayout.itemSize = CGSizeMake(ItemWH,ItemWH)
        
        flowLayout.minimumInteritemSpacing = ItemMargin
        flowLayout.minimumLineSpacing = ItemMargin
        
        
        self.dataSource = self
        
        self.delegate = self
        
        //注册cell
        registerClass(SWPictureCell.self, forCellWithReuseIdentifier: SWPictureImageViewCellID)
        
        self.backgroundColor = UIColor.whiteColor()
 
    }
    
        
}
    
    
  
// MARK: - UICollectionViewDataSource

extension SWPictureCollectionView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SWPictureImageViewCellID, forIndexPath: indexPath) as! SWPictureCell
        
        cell.picModel = dataArray![indexPath.row]
   
     //   cell.backgroundColor = RandomColor()
        
        return cell
  
    }
    
    
    
}